<template>
  <div style="height: 100%; height: 100%; position: relative;">
    <div style="height: 100%; height: 100%; position: relative" ref="D3_dom">
      <p style="position:absolute;top: 10px;left: 10px;font-size: 16px;color: #fff;">12层</p>
      <!-- <p style="position:absolute;top: 10px;left: 10px;font-size: 16px;color: #fff;">倍速:{{ isSpeed }}--是否播放{{isPlay}}---12层</p> -->
    </div>
    <!-- css模型对象 人员信息 -->
    <div  id="box_people"   ref="box_people">
      <div class="box_people_title">
        <p>项目信息：{{ xmName }}</p> 
      </div>
      <div class="box_people_content">
          <div class="box_people_content_img">
             <div style="padding-left: 20px;padding-top: 30px;width: 70px;height:82px"><TouimgComponent   :src="touxianglist[0]"/></div>
          </div>
          <div class="box_people_content_msg">
            <ul>
              <li><span>姓名：{{ curItemMsg.personName }}</span></li>
              <li><span>违规行为：{{ curItemMsg.alarmName }}</span></li>
              <li><span>当前位置：{{ curItemMsg.alarmAddress }}</span></li>
              <li><span>违规时间：{{ curItemMsg.alarmTime }}</span></li>
              <li><span>视频查看：</span><span> 
                <!-- <button @click="handelePlay(item)">点击播放</button> -->
              </span></li>
            </ul>
          </div>
      </div>
    </div>

    <!-- 报警信息 -->
     <!-- <div id="wangerMsg"  ref="wangerMsg">
       <div><span><img  :src="require('@/assets/imgs/dp/预警icon.png')" alt=""></span><span style="margin-left:8px">预警广播</span></div>
       <p class="wangerMsg_content">{{ wangerMsg }}</p>
     </div> -->
     <!-- 进度条 -->
    
     <ProgressComponent :onClearCanvas="clearCanvas"  :longTime="longTime" :onChange3D="onChange3D" :timeStart="timeStart"  :pointsData="pointsData" style="position: absolute;bottom: 50px;"/>
  </div>

</template>
  
  <script>
// 14.平行四边形
// #parallelogram{
// width: 200px;
// height: 150px;
// margin-left: 30px;
// -webkit-transform: skew(-30deg);
// -moz-transform: skew(200deg);
// -o-transform: skew(200deg);
// background-color: red;
// }
import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
import { CSS2DObject } from 'three/examples/jsm/renderers/CSS2DRenderer.js' ;
import { CSS2DRenderer } from 'three/examples/jsm/renderers/CSS2DRenderer.js';
import { EffectComposer } from "three/examples/jsm/postprocessing/EffectComposer.js"
import { RenderPass } from "three/examples/jsm/postprocessing/RenderPass.js"
import { OutlinePass } from "three/examples/jsm/postprocessing/OutlinePass.js"
import { OutputPass } from 'three/examples/jsm/postprocessing/OutputPass.js';
import { LineGeometry } from "three/examples/jsm/lines/LineGeometry.js"
import { Line2 } from "three/examples/jsm/lines/Line2.js"
import { LineMaterial } from "three/examples/jsm/lines/LineMaterial";
import { GUI } from "three/examples/jsm/libs/lil-gui.module.min"
import { TextGeometry } from 'three/examples/jsm/geometries/TextGeometry.js';
import { Tween, Group } from '@tweenjs/tween.js'
import  * as GeometryUtils from 'three/examples/jsm/utils/GeometryUtils'
import  {createText} from 'three/examples/jsm/webxr/Text2D'
import model,{ mesh,meshWanger,meshWangerT} from "@/views/witness/components/Object3D/canvas/model_item"; //模型对象
 import TouimgComponent from "@/views/witness/components/Object3D/touimgComponent.vue" 
import ProgressComponent  from "./progress.vue"
import louceng_JSON from "@/views/witness/components/Object3D/canvas/louceng.json"
import { peopList } from "@/views/witness/components/Object3D/canvas/const"

export default {
  props:{
    onGetPersColor:{
      type:Function,
      default:()=>[]
    },
    xmName:{
      type:String,
      default:''
    }
  },
  components:{
        TouimgComponent,
        ProgressComponent
      },
  data() {
    return {
      //播放器
      isSpeed:1,
      isPlay:false,
      longTime:0, // 轨迹总时长
      timeStart:'YYYY-MM-DD 00:00:00', // 轨迹开始时间
      // 默认头像
      touxianglist:[require('@/assets/imgs/dp/专家.png'),require('@/assets/imgs/dp/专家2.png'),require('@/assets/imgs/dp/专家3.png')],
      D3data: {},
      peopList,
      curItemMsg:{
      },
      wangerMsg:'',
      Wangerdata:[
        {
          username:'张三1',
          type:'甲方代表',
          name:'1神木市傻茆帧王家洼村与王家庄村互联互通道路硬化工程',
          wfxw:'离开评标区',
          weizhi:'卫生间1',
          time:'2020-22-22 09:45:57',
          url:'',
          img:'',
          position:['100','100']
        },
        {
          username:'张三2',
          type:'甲方代表',
          name:'2神木市傻茆帧王家洼村与王家庄村互联互通道路硬化工程',
          wfxw:'离开评标区',
          weizhi:'卫生间2',
          time:'2020-22-22 09:45:57',
          url:'',
          img:'',
          position:['100','300']
        },
        {
          username:'张三3',
          type:'甲方代表',
          name:'3神木市傻茆帧王家洼村与王家庄村互联互通道路硬化工程',
          wfxw:'离开评标区',
          weizhi:'卫生间3',
          time:'2020-22-22 09:45:57',
          url:'',
          img:'',
          position:['200','100']
        },

      ],
      peopleList: [],
      textarea: "",
      pos:{
        x: 0,
        y: 0,
        z: 0
      },
      positions :[], // 全部数据
      pointsData:[], // 全部数据传给子组件
      points:[] // 部分数据
    };
  },
  created(){
    // this.handlecurTime()
  },
  methods: {
    // 画线
    onChange3D(lineData){
      const prambox = model.children[0] // 场地模型
      const lineGeometry  = new LineGeometry();
    
      
        // 遍历渲染模型
       for(let i in lineData){
        const { color,groupName,NeedUpdate_waring,NeedUpdate,xuanranPoints_waring_time,line2Name, wangerName,circleName} = lineData[i]
        let { xuanranPoints ,xuanranPoints_waring } = lineData[i]
        const lineMaterial =  new LineMaterial({
              color,
              vertexColors:false,
              linewidth:2, 
              resolution: new THREE.Vector2(window.innerWidth, window.innerHeight), // 分辨率  // worldUnits: true, // false 表示单位像素
            })
        const group =  prambox.getObjectByName(groupName)
        if(!group){  // 没有该组 并且轨迹数据不为空
            console.log('重新创建');
            
             const Group = new THREE.Group()
             const group = Group.clone()
             const group_wanger = Group.clone()
            //  let position =  new THREE.Vector3();
                   group_wanger.name = wangerName //预警组
                  //  group.getWorldPosition(position)
                  //  group_wanger.position.set(...position)
  
                  // const testGeometry = new THREE.PlaneGeometry (944, 265);
                  // testGeometry.translate(944/2,265/2,0); 
                  // const testWanger = new THREE.MeshLambertMaterial({
                  //     transparent:true,
                    
                  //     // alphaMap:new THREE.Color('#fff')
                  // })
                  //  const meshtest = new THREE.Mesh(testGeometry, testWanger);
                  //  meshtest.position.set(0,0,0)




                  // group.add(meshtest)
                  group.add(group_wanger)
                  group.name = groupName
                  prambox.add(group)
              
         }
        if(group && NeedUpdate) { //如果线需要更新
          let linePeople =  group.getObjectByName(line2Name)
          if(!linePeople){
              // 创建线
              const geometry = lineGeometry.clone()
              geometry.setPositions(xuanranPoints)
              const  material = lineMaterial.clone()
              const line2 = new Line2(geometry,material)
              const geometry_cir = new THREE.CircleGeometry( 5, 32 );
              const material_cir = new THREE.MeshBasicMaterial({color});
              const circleMesh = new THREE.Mesh( geometry_cir, material_cir );
              circleMesh.name = circleName
              circleMesh.position.set(...xuanranPoints.slice(-3))
              line2.geometry.dynamic = true;
              line2.geometry.attributes.position.needsUpdate = true;
              line2.name = line2Name
              line2.computeLineDistances()
              line2.add(circleMesh)
              group.add(line2)
              linePeople =  group.getObjectByName(line2Name)
          }
          const circleMesh = group.getObjectByName(circleName) 
                circleMesh.position.set(...xuanranPoints.slice(-3))
               linePeople.geometry.dispose() 
          const geometry =  lineGeometry.clone();
                geometry.setPositions(xuanranPoints)
                linePeople.geometry = geometry
        }
        if(group && NeedUpdate_waring){ //如果预警需要更新 wangerName
          const group =  prambox.getObjectByName(groupName)
          const group_wanger =  group.getObjectByName(wangerName)
          const num = group_wanger.children.length 
          xuanranPoints_waring = [...xuanranPoints_waring]
          for(let s in xuanranPoints_waring) {
               if(s >= num){
                const wangerMesh = meshWanger.clone()
                wangerMesh.position.set(...xuanranPoints_waring[s])
                wangerMesh.name = xuanranPoints_waring_time[s]
                wangerMesh.warngerIndex =  s
                group_wanger.add(wangerMesh)
               }
            }
          }
       }
    },
    // 设置房间名称
    async setRoomName (){
        // 处理房间
        const prambox = model.children[0] // 场地模型
        const arr = louceng_JSON['12层'].map(item=>{
          item.roomName = item.name.split('-')[1] || item.name.split('-')[0]
          return { ...item,}
        })
        for (const i in arr) {
          const text =  createText(arr[i].roomName,6)
          text.position.set(Number(arr[i].x), arr[i].y,0)
          prambox.add( text );
        }
        // const data = louceng_JSON.filter(x=>x.type === '1')
        // console.log(data);
     
        
      
     
      
      // const loader = new FontLoader();

      // loader.load( 'fonts/helvetiker_regular.typeface.json', function ( font ) {
      //   const geometry = new TextGeometry( 'Hello three.js!', {
      //     font: font,
      //     size: 80,
      //     depth: 5,
      //     curveSegments: 12,
      //     bevelEnabled: true,
      //     bevelThickness: 10,
      //     bevelSize: 8,
      //     bevelSegments: 5
      //   });
      // });
     
      
    },
    // 设置警告
    setWanger (data){
      // model.add()
      if(data.length <= 0) return 
      const prambox = model.children[0]
      let i = 0 
      const myInterval = setInterval(()=>{
        const obj = meshWanger.clone()
          obj.name = '警告'
          obj.mssage = data[i]
          obj.position.set(data[i].xyz[0]*10,data[i].xyz[1]*10,0)
          prambox.add(obj)
          const { personName,personType,} = data[i]
            this.wangerMsg = `${personName}${peopList[personType]}请您遵守评标纪律，尽快回到您的评标岗位！`
          if(i>= data.length - 1){
            clearInterval(myInterval)
          } 
          i++
      },100)
      //清除计时器
      
    },
    setWangerMsg() {
           // 将css元素添加到模型中
           const DivWangerMsg =  this.$refs["wangerMsg"] 
          const DivModelDivWangerMsg= new CSS2DObject(DivWangerMsg);
          DivModelDivWangerMsg.position.set(680,340,0)
          model.traverse((obj)=>{
            if (obj.isMesh && obj.name === '场地') {
                  obj.add(DivModelDivWangerMsg)
              }
          })
      

    },
    // 创建css2渲染器
    setCss2(){
    },
    // 时间自动播放
    handlecurTime(){

      function formatDuration(totalSeconds) {
          const hours = Math.floor(totalSeconds / 3600);
          const minutes = Math.floor((totalSeconds % 3600) / 60);
          const seconds = Math.floor(totalSeconds % 60);

          return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
        }
      const itmp = 1000 // 1s
      let curTime = 0
      setInterval(()=>{
        curTime += 1000
       this.curTime = formatDuration(curTime/1000)
      },itmp)
    },
    // 计算总时长
    formatDurationlog(diffMilliseconds){
      // // 创建两个日期对象
      //   const startDate = new Date('2023-10-01T00:00:00Z');
      //   const endDate = new Date('2023-10-02T12:30:45Z');
      //   console.log('startDate',startDate);
      //   console.log('endDate',endDate);
      //   // 计算时间差（以毫秒为单位）
      //   const diffMilliseconds = endDate - startDate;

        // 将时间差转换为秒、分钟、小时和天
        const diffSeconds = diffMilliseconds / 1000;
        const diffMinutes = diffSeconds / 60;
        const diffHours = diffMinutes / 60;
        const diffDays = diffHours / 24;
        // console.log(`总时长（毫秒）: ${diffMilliseconds}`);
        // console.log(`总时长（秒）: ${diffSeconds}`);
        // console.log(`总时长（分钟）: ${diffMinutes}`);
        // console.log(`总时长（小时）: ${diffHours}`);
        // console.log(`总时长（天）: ${diffDays}`);
        // 格式化为 HH:MM:SS
        function formatDuration(totalSeconds) {
          const hours = Math.floor(totalSeconds / 3600);
          const minutes = Math.floor((totalSeconds % 3600) / 60);
          const seconds = Math.floor(totalSeconds % 60);

          return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
        }
        this.longTime = formatDuration(diffSeconds)
        // console.log(`总时长（HH:MM:SS）: ${formatDuration(diffSeconds)}`);
    },

    // 画多条轨迹
    handleLineAll(data){
      const prambox = model.children[0] // 场地模型
      // 清除所有线条
      const calc = 10 // 实际米数比值
      const JG = 1 // 每人轨迹间隔
      
      const color = new THREE.Color()
      const persColor = []
      let timeStampLog = 0
      let timeStart = '00:00:00'  // YYYY - MM - DD HH:MM:SS
      for(const [index,item] of Object.entries(data)){
          // 轨迹
          item.points= [] // 坐标[（x,y,z）]
          item.times = [] // 时间
          item.positions = [] // 轨迹点 [x,y,z,x1,y1,z1,] // 经过三维样条曲线 插值  // 只有轨迹点没有
          item.timeStamps = [] // 轨迹时间戳
          // 预警
          item.points_waring = []
          item.times_waring = [] 
          item.timeStamps_waring = []
          // 基础数据
          color.setHSL(Math.random(),1.0,0.5)
          item.color =color.clone()
          item.colors = [] // 颜色
          item.setInterval = null
          item.groupName  =  'group-'+item.personId
          item.line2Name  =  'line2-'+item.personId
          item.wangerName  =  'Plane-'+item.personId
          item.wangerName  =  'Plane-'+item.personId
          item.circleName  =  'circle-'+ item.personId
          persColor.push({personId:item.personId,HexString: '#' + item.color.getHexString()})
          const trackList = item.trackList
          const len = trackList.length 
          // 处理最长时间
          item.statTime =  trackList[0].dateTime
          item.endTime =  trackList.at(-1).dateTime
          const statTime = new Date(item.statTime)
          const endTime = new Date(item.endTime)
          item.timeStamp = endTime - statTime
          if(timeStampLog < item.timeStamp ){
            timeStampLog = item.timeStamp 
            timeStart = item.statTime
          }
        
          // 循环创建数据
          for(let i= 0; i< len; i++){
            if(trackList[i].type === 0){ // 路径
              const [x,y,z] = trackList[i].pos
              item.points.push(new THREE.Vector3(x * calc + JG * index,y * calc + JG * index,z));
              item.times.push(trackList[i].dateTime)
              item.timeStamps.push(trackList[i].timestamp)
            }
            if(trackList[i].type === 1){ // 告警
              const [x,y,z] = trackList[i].pos
              item.points_waring.push(new THREE.Vector3(x * calc + JG * index,y * calc + JG * index,z))
              item.times_waring.push(trackList[i].dateTime) 
              item.timeStamps_waring.push(trackList[i].timestamp)
            }
          }
          const spline = new THREE.CatmullRomCurve3(item.points)
          const point = new THREE.Vector3();
          for(const it in item.points){ // 处理轨迹取点
            const t =  it / item.points.length;
            spline.getPoint(t, point);
            item.positions.push(point.x, point.y, point.z)
            // color.setHSL(t,1.0,0.5);
            // item.colors.push(color.r,color.g,color.b)
          }
          // const geometry  = new LineGeometry();
          // geometry.setPositions(item.positions.slice(0, 12  ))
          // geometry.setColors(item.color)
            //  创建线材质
          // const material =  new LineMaterial({
          //     color:item.color,
          //     vertexColors:false,
          //     // worldUnits: true, // false 表示单位像素
          //     linewidth:2,
          //     resolution: new THREE.Vector2(window.innerWidth, window.innerHeight), // 分辨率
          //     // dashed:true,
          //     // dashSize: 0.5,
          //     // gapSize: 0.5
          //   })
          //   // 创建线
          //   const line2 = new Line2(geometry,material)
          //   line2.geometry.dynamic = true;
          //   line2.geometry.attributes.position.needsUpdate = true;
          //   line2.name = item.id
          //   line2.computeLineDistances()
          //   prambox.add(line2)
          //   // 创建圆头像
          //   const geometry_cir = new THREE.CircleGeometry( 5, 32 );
          //   const material_cir = new THREE.MeshBasicMaterial( { 
          //     color: item.color,
          //     // wireframe: true,
          //     // depthTest: false,
          //     // depthWrite: false,
          //    } );
            // const circleMesh = new THREE.Mesh( geometry_cir, material_cir );
            // prambox.add(circleMesh)
            // // 动态画线
            // const pointsBuf = []
            // // console.log('item',item);
            // //  console.log(line2.geometry.setDrawRange);
            // // line.geometry.setDrawRange( 0, newValue );
            // // line.geometry.attributes.position.needsUpdate = true; 
            // let count = 0
            // item.setInterval = setInterval(() => {
            //   line2.geometry.dispose() 
            //   pointsBuf.push(item.points[count].x, item.points[count].y, item.points[count].z)
            //   line2.geometry = new LineGeometry().setPositions(pointsBuf)
            //   circleMesh.position.set(item.points[count].x, item.points[count].y, item.points[count].z)
            //   line2.add(circleMesh)
            //   count++;
            //   if( count > (item.points.length -1)) {
            //   clearInterval(item.setInterval)
            //   }
            // }, 100);
      }
      this.longTime = timeStampLog // 轨迹总长度
      this.timeStart =   timeStart // 轨迹开始时间
      this.pointsData =  data
      // 给父组件传递颜色数据
      this.onGetPersColor(persColor)
      // 清空画布
      this.clearCanvas()
    },
   clearCanvas() {
      const prambox = model.children[0] 
        while (prambox.children.length > 0) {
          if(prambox.children[0])
          prambox.remove(prambox.children[0]);
        }
        this.setRoomName()
      },
    handleLine(data){
      const points = [];
      const times = [];
      for (let i = 0; i < data.length; i++) {
        let  [x,y,z] = data[i].pos
        let calc =  10
        const time = 3 * i
        times.push(time)
        points.push(new THREE.Vector3(x*calc,y*calc,z));
      }
      const spline = new THREE.CatmullRomCurve3(points)
      const positions = []
      const colors = []
      const point = new THREE.Vector3();
      const color = new THREE.Color()
      for (let i = 0,l = points.length; i<l;i++) {
        const t =  i / l;
        spline.getPoint(t, point);
        positions.push(point.x, point.y, point.z)
        color.setHSL(t,1.0,0.5);
        colors.push(color.r,color.g,color.b)
      }
      const geometry  = new LineGeometry();
      geometry.setPositions(positions.slice(0, 3))
      geometry.setColors(colors)
      const material =  new LineMaterial({
        color:0xffffff,
        vertexColors:true,
        // worldUnits: true, // false 表示单位像素
        linewidth:3,
        resolution: new THREE.Vector2(window.innerWidth, window.innerHeight), // 分辨率
        // dashed:true,
        // dashSize: 0.5,
        // gapSize: 0.5
      })
      const line2 = new Line2(geometry,material)
      line2.geometry.dynamic = true;
      line2.geometry.attributes.position.needsUpdate = true;
      line2.name = 'BoxLine2'
      line2.computeLineDistances()
      const prambox = model.children[0]
      prambox.add(line2)
       let pointsBuf = []
       let count = 0;
       setInterval(() => {
             line2.geometry.dispose() 
             pointsBuf.push(points[count].x, points[count].y, points[count].z)
            line2.geometry = new LineGeometry().setPositions(pointsBuf)
            line2.geometry.setColors(colors)
            count++;
        if( count > (data.length -1)) count = 0
       }, 100);
    },
    startAnimation() {
    },
    animate(time) {
      requestAnimationFrame(this.animate);
      this.group.update(time)
    },
    // 关键帧动画弃用
    keyAnm(){
      const values = points
      const posKF = new THREE.KeyframeTrack('BoxLine2.geometry.attributes.position', times, values)
      // const colorKF = new THREE.KeyframeTrack('BoxLine2.material.color', times, [1,0,0,0,0,1])
      const  clip = new THREE.AnimationClip('Action', times.at(-1), [posKF])
      const mixer = new THREE.AnimationMixer(line2);
       const clipAction = mixer.clipAction(clip)
       clipAction.play()
       clipAction.loop = THREE.LoopOnce // 只播放一次
       clipAction.clampWhenFinished = true // 动画播放结束位置
       clipAction.timeScale = 0.5 //播放倍速
        // clipAction.time = 1 // 从第一秒开始播放
        // clipAction.duration = 5 //到多少s结束
        // clipAction.paused = true // 暂停
        const gui = new GUI()
        gui.add(clipAction, 'time',0,times.at(-1)).name('播放进度条')
        const clock = new THREE.Clock()
      //   function loop (){
      //     requestAnimationFrame(loop)
      //     const frameT = clock.getDelta()
      //     mixer.update(frameT)
      // }
      // loop()
    },
    // 创建线
    handleLine2(data){
      // 创建轨迹的几何体
      const points = [];
      for (let i = 0; i < data.length; i++) {
        let  [x,y,z] = data[i].pos
        let calc =  10
          points.push(new THREE.Vector3(x*calc,y*calc,z));
      }

      const geometry = new THREE.BufferGeometry().setFromPoints(points);
      // 创建材质 红色：0xff0000
        const material = new THREE.LineBasicMaterial(
          { color: new THREE.Color('#54b7f6'),linewidth:3 });
        // 创建线条对象
        const line = new THREE.Line(geometry, material);
        // const axesHelper = new THREE.AxesHelper(100);
        // line.add(axesHelper)
        const prambox = model.children[0]
      //  const changdi =  this.D3data.scene.getObjectByName('场地');
      // line.position.
      prambox.add(line)
      //  console.log(this.D3data.scene.children[0]);
      // console.log('changdi',changdi);
      // this.D3data.scene.add(line); 
    },
    // 
    initDiv() {
      
      // 获取dom节点
      const width = this.$refs["D3_dom"].offsetWidth;
      const height = this.$refs["D3_dom"].offsetHeight;
      //场景
      const scene = new THREE.Scene();
      let selectedObjects = []
      // scene.background = new THREE.Color('#7b7e80');
      scene.background = null;
      scene.add(model);
      // model.children[0].geometry.translate(985/2,277/2,0); 

      // 总辅助坐标系
      // const axesHelper = new THREE.AxesHelper(100);
      // scene.add(axesHelper);

      // 添加一个辅助网格地面 1468 × 400
      // const gridHelper = new THREE.GridHelper(1468, 400, 0x004444, 0x004444);
      // scene.add(gridHelper);

      //光源设置
      const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
      directionalLight.position.set(100, 60, 50);
      scene.add(directionalLight);
      const ambient = new THREE.AmbientLight(0xffffff, 2);
      scene.add(ambient);
      //渲染器和相机
      const camera = new THREE.PerspectiveCamera(30, width / height, 1, 3000);
      camera.position.set(0, 0, 950);
      camera.lookAt(0, 0, 0);
      const renderer = new THREE.WebGLRenderer();
      renderer.setSize(width, height);
      renderer.setClearAlpha(0);
      renderer.setPixelRatio(window.devicePixelRatio); //防止输出模糊
      renderer.outputEncoding = THREE.sRGBEncoding;
      this.$refs["D3_dom"]?.appendChild(renderer.domElement);
      // document.body.appendChild(renderer.domElement);
      // const div = document.getElementById ('tag');、
      // 将css元素添加到模型中
      //      const Div_box_people =  this.$refs["box_people"] 
      // const Div_model_box_people = new CSS2DObject(Div_box_people);
      //         //改变图片网格模型顶点坐标
      // //       // Div_model_box_people.position.set(pos.getX(0),pos.getY(0),pos.getZ(0));
      // model.children[0].add(Div_model_box_people);  //插入css弹框
      // css2渲染器
      const css2Renderer = new CSS2DRenderer();
      css2Renderer.setSize(width, height);
      css2Renderer.domElement.style.position = 'absolute';
      css2Renderer.domElement.style.top = '0px';
      // css2Renderer.domElement.style.display='none';
      css2Renderer.domElement.style.pointerEvents = 'none' ;
      this.$refs["D3_dom"]?.appendChild(css2Renderer.domElement);
      //后处理
      // 创建渲染器通道
      const composer = new EffectComposer(renderer);
      const renderPass = new RenderPass(scene,camera);
      composer.addPass(renderPass);
      const outputPass = new OutputPass();
      composer.addPass( outputPass );
      // 创建outlinePass通道
      const v2 = new THREE.Vector2(width, height);
      const outlinePass = new OutlinePass(v2, scene, camera);
      outlinePass.visibleEdgeColor.set(0x00ffff);
      outlinePass.edgeThickness = 4;
      // console.log();
      // const xx = model.children[0].children[0]
      // outlinePass.selectedObjects = [ xx];
      // outlinePass.selectedObjects = model.children[0].children;
      outlinePass.edgeStrength = 6;
      composer.addPass(outlinePass);
      function addSelectedObject( object ) {
        selectedObjects = [];
        selectedObjects.push( object );
      }
      // 坐标拾取
      renderer.domElement.addEventListener('click',(event)=>{
      
      
      const px = event.offsetX;
      const py = event.offsetY;
      // 屏幕坐标px,py 转WebGL标准设备坐标x,y
      // width ,height 画布宽高度
      const x = (px/width) * 2 - 1;
      const y = - (py/height) * 2 + 1;
      const raycaster = new THREE.Raycaster();
      raycaster.setFromCamera(new THREE.Vector2(x,y),camera)
      const intersects = raycaster.intersectObjects(model.children[0].children)
     
      
      if(intersects.length > 0  ){
        // console.log('xx',intersects[0].object.name        );
        if(intersects[0].object.name !== '警告') return 
        const selectedObject = intersects[0].object;
        addSelectedObject(selectedObject)
        outlinePass.selectedObjects = selectedObjects;
        document.querySelector('#box_people').style.display = "block"
        // console.log('event',event.offsetX,event.offsetY)
        document.querySelector('#box_people').style.top= event.offsetY +'px'
        document.querySelector('#box_people').style.left= event.offsetX +'px'
        // outlinePass.selectedObjects = [intersects[0].object];
        // 选中模型的第一个模型，设置为红色
        // console.log('selectedObject.message',selectedObject.mssage);
        this.curItemMsg = selectedObject.mssage
        console.log('curItemMsg',this.curItemMsg);
        
        // this.refs['box_people'].style.display = "block"
        intersects[0].object.material.color.set(0xff0000); 
      }else{
          // this.refs['box_people'].style.display = "none"
           document.getElementById('box_people').style.display = "none"
      }
    
     })
      const controls = new OrbitControls(camera, renderer.domElement);
      // 缩放范围
      controls.target.set(0, 0, 0); //与lookAt参数保持一致
      controls.update(); //update()函数内会执行camera.lookAt(controls.target)
      controls.enableRotate = false; // 禁止旋转
      // controls.enableZoom = false; //禁止缩放
      // //相机位置与观察目标点最小值
      // controls.minDistance = 800;
      // //相机位置与观察目标点最大值
      // controls.maxDistance = 1500;
      controls.maxTargetRadius = 400
      controls.mouseButtons = {
          //左键平移
          LEFT: THREE.MOUSE.PAN,
          //滚轮滑动
          MIDDLE: THREE.MOUSE.DOLLY,
          //右键旋转
          RIGHT: THREE.MOUSE.ROTATE,
      };

      // 用不到
      // controls.minZoom = -1;
      // controls.maxZoom = 2;
      // controls.update();
      // controls.minTargetRadius  =
      // controls.touches = {
      //                         ONE: THREE.TOUCH.DOLLY_PAN ,
      //                         TWO: THREE.TOUCH.ROTATE,
      //                     }
      controls.update();

    
      // 画布跟随窗口变化
      return {
        scene,
        controls,
        renderer,
        camera,
        css2Renderer,
        composer,
        outlinePass
      };
    },
    // 播放设备
    handelePlay(item){
    },
    // 屏幕坐标转标准设备坐标
    changXY(camera,renderer,outlinePass){
      const width = this.$refs["D3_dom"].offsetWidth;
      const height = this.$refs["D3_dom"].offsetHeight;
      renderer.domElement.addEventListener('click',function(event){
      const px = event.offsetX;
      const py = event.offsetY;
      // 屏幕坐标px,py 转WebGL标准设备坐标x,y
      // width ,height 画布宽高度
      const x = (px/width) * 2 - 1;
      const y = - (py/height) * 2 + 1;
      // console.log('x',x);
      // console.log('y',y);
      const raycaster = new THREE.Raycaster();
      raycaster.setFromCamera(new THREE.Vector2(x,y),camera)
      const intersects = raycaster.intersectObjects(model.children)
      if(intersects.length > 0 ){
        // console.log(intersects[0]);
        outlinePass.selectedObjects = [model.children];
        // 选中模型的第一个模型，设置为红色
        intersects[0].object.material.color.set(0xff0000); 
       
      } 
      
     })
   


    },
    handleGoLeft(flg) {
      this.$refs["flexUl"].scrollBy({
        top: 0,
        left: !flg ? 90 : -90,
        behavior: "smooth"
      });
    },
    handleClear() {
      this.D3data.scene.traverse(function (obj) {
        if (obj.isMesh) {
          //判断是否是网格模型
          obj.material.color.set(new THREE.Color("#fff"));
        }
      });
    },
    handleSelect(name) {
      // 0x00FFFFFF
      this.D3data.scene.getObjectByName(name).material.color.set(new THREE.Color("#CD5C5C"));
    },
    debounce(fn, delay) {
      const delays = delay || 500;
      let timer;
      return function () {
        const th = this;
        const args = arguments;
        if (timer) {
          clearTimeout(timer);
        }
        timer = setTimeout(function () {
          timer = null;
          fn.apply(th, args);
        }, delays);
      };
    }
  },
 
  mounted() {
    this.D3data = this.initDiv();
    window.onresize = () => {
        const width = this.$refs["D3_dom"].offsetWidth;
        const height = this.$refs["D3_dom"].offsetHeight;
        this.D3data.renderer.setSize(width, height);
         this.D3data.css2Renderer.setSize(width, height);
        this.D3data.camera.aspect = width / height;
        this.D3data.camera.updateProjectionMatrix();
    }; 


     // 渲染循环
     const  render = () => {
        // this.group.update(time)
        // this.D3data.renderer.render(this.D3data.scene, this.D3data.camera);
        this.D3data.composer.render()
        this.D3data.css2Renderer.render(this.D3data.scene, this.D3data.camera);
        requestAnimationFrame(render);
      }
      render();
      // this.setWangerMsg()
      this.setRoomName()
  },
  destroyed(){
      window.onresize = null;
      this.clearCanvas()
      
   }
};
</script>
  
  <style scoped lang="scss">
  $font14: 14px; 
.button_box {
  position: absolute;
  top: 10px;
  left: 10px;
}
#box_people {
  cursor: default;
  display: none;
  position: absolute;
  width: 424px;
  height: 330px;
  padding: 4px 6px;
  color: #fff;
  background-image: url("../../../../assets/imgs/dp/弹窗背景2.png");
  background-size: 100% 100%;
  // background-attachment:fixed;
  .box_people_title {
    height: 70px;
    line-height: 30px;
  }
  .box_people_content{
    height: 270px;
    display: flex;
    align-items: center;
   
    .box_people_content_img{
      width: 150px;
      height: 230px;
      background-image: url('../../../../assets/imgs/dp/头像未选中背景@2x.png');
      background-repeat: no-repeat;
      background-size: 100% auto;
     
    }
    .box_people_content_msg{
      button{
        border: 1px solid #fff;
        color: #0A6ACF;
      }
      // height: 230px;
      li{
        height: 40px;
      }
    }
  }
  

 
}
#wangerMsg {
  width: 200px;
  padding: 10px 14px;
  height: 122px;
  background:url('../../../../assets/imgs/dp/预警背景.png');
  background-size: 100% 100%;
  img{
    width: 20px;
    height: 18px;
  }
  p{
    line-height: 30px;
  }
  .wangerMsg_content{
    margin-top: 6px;
  }
  color: #fff;
 
}





</style>
  